package datastructure.array;

import java.util.ArrayList;
import java.util.List;

/**
 * http://www.geeksforgeeks.org/archives/8133
 *
 * @author Lei Zhang
 */
public class DutchFlagProblem {

    /**
     *
    Given an array A[] consisting 0s, 1s and 2s, write a function that sorts A[].
    The functions should put all 0s first, then all 1s and all 2s in last.
    
    Example
    Input = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
    Output = {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2}
     *
     * @param A
     */
    public static void dutchFlagProblem(int[] A) {

        int low = 0;
        int middle = 0;
        int high = A.length - 1;

        while (middle <= high) {
            if (A[middle] == 0) {
                exchange(A, low, middle);
                low++;
                middle++;
            }
            else if (A[middle] == 1) {
                middle++;
            }
            else if (A[middle] == 2) {
                exchange(A, middle, high);
                high--;
            }
        }
    }

    private static void exchange(int[] A, int i, int j) {
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }

 

    public static void main(String args[]) {
        int arr[] = {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1};
        DutchFlagProblem.dutchFlagProblem(arr);

        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

//        printTriangle(4);

    }
}
